<script setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { areaData } from '@/data/china-area-data'

// 地址列表
const addresses = ref([
  {
    id: 1,
    name: '张三',
    phone: '13800138000',
    province: '北京市',
    city: '北京市',
    district: '朝阳区',
    address: '三里屯SOHO',
    isDefault: true
  },
  {
    id: 2,
    name: '李四',
    phone: '13900139000',
    province: '上海市',
    city: '上海市',
    district: '浦东新区',
    address: '陆家嘴',
    isDefault: false
  }
])

// 编辑地址对话框
const dialogVisible = ref(false)
const selectedArea = ref([])
const editingAddress = ref({
  id: null,
  name: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  address: '',
  isDefault: false
})

// 打开编辑对话框
const openEditDialog = (address = null) => {
  if (address) {
    editingAddress.value = { ...address }
    selectedArea.value = [address.province, address.city, address.district]
  } else {
    editingAddress.value = {
      id: Date.now(),
      name: '',
      phone: '',
      province: '',
      city: '',
      district: '',
      address: '',
      isDefault: false
    }
  }
  dialogVisible.value = true
}

// 监听选择的地区变化
watch(selectedArea, (newValue) => {
  if (newValue && newValue.length === 3) {
    editingAddress.value.province = newValue[0]
    editingAddress.value.city = newValue[1]
    editingAddress.value.district = newValue[2]
  }
})

// 保存地址
const saveAddress = () => {
  addressFormRef.value.validate((valid) => {
    if (valid) {
      // 这里应该调用API保存地址
      // API调用后端
      // saveAddressAPI(currentAddress.value).then(() => {
      //   ElMessage.success('地址保存成功')
      //   addressDialogVisible.value = false
      //   loadAddresses()
      // })
      
      // 模拟保存成功
      if (currentAddress.value.id) {
        // 更新现有地址
        const index = addresses.value.findIndex(addr => addr.id === currentAddress.value.id)
        if (index !== -1) {
          addresses.value[index] = { ...currentAddress.value }
        }
      } else {
        // 添加新地址
        currentAddress.value.id = Date.now() // 模拟ID生成
        addresses.value.push({ ...currentAddress.value })
      }
      ElMessage.success('地址保存成功')
      addressDialogVisible.value = false
    }
  })
}

// 删除地址
const deleteAddress = (address) => {
  // 这里应该调用API删除地址
  // API调用后端
  // deleteAddressAPI(address.id).then(() => {
  //   ElMessage.success('地址删除成功')
  //   loadAddresses()
  // })
  
  // 模拟删除成功
  const index = addresses.value.findIndex(addr => addr.id === address.id)
  if (index !== -1) {
    addresses.value.splice(index, 1)
  }
  ElMessage.success('地址删除成功')
}

// 设置默认地址
const setDefaultAddress = (address) => {
  // 这里应该调用API设置默认地址
  // API调用后端
  // setDefaultAddressAPI(address.id).then(() => {
  //   ElMessage.success('已设为默认地址')
  //   loadAddresses()
  // })
  
  // 模拟设置成功
  addresses.value.forEach(addr => {
    addr.isDefault = addr.id === address.id
  })
  ElMessage.success('已设为默认地址')
}
</script>

<template>
  <el-card class="address-card">
    <template #header>
      <div class="card-header">
        <h3>地址管理</h3>
        <el-button type="primary" @click="openEditDialog()">
          添加新地址
        </el-button>
      </div>
    </template>
    
    <el-empty v-if="addresses.length === 0" description="暂无收货地址" />
    
    <div v-else class="address-list">
      <el-card
        v-for="address in addresses"
        :key="address.id"
        class="address-item"
        :class="{ 'is-default': address.isDefault }"
        shadow="hover"
      >
        <div class="address-info">
          <div class="address-header">
            <span class="name">{{ address.name }}</span>
            <span class="phone">{{ address.phone }}</span>
            <el-tag v-if="address.isDefault" type="success" size="small">
              默认地址
            </el-tag>
          </div>
          <div class="address-detail">
            {{ address.province }} {{ address.city }} {{ address.district }} {{ address.address }}
          </div>
        </div>
        
        <div class="address-actions">
          <el-button
            v-if="!address.isDefault"
            type="primary"
            text
            @click="setDefaultAddress(address.id)"
          >
            设为默认
          </el-button>
          <el-button
            type="primary"
            text
            @click="openEditDialog(address)"
          >
            编辑
          </el-button>
          <el-button
            v-if="!address.isDefault"
            type="danger"
            text
            @click="deleteAddress(address.id)"
          >
            删除
          </el-button>
        </div>
      </el-card>
    </div>
    
    <!-- 编辑地址对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="editingAddress.id ? '编辑地址' : '新增地址'"
      width="500px"
    >
      <el-form :model="editingAddress" label-width="100px">
        <el-form-item label="收货人">
          <el-input v-model="editingAddress.name" />
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="editingAddress.phone" />
        </el-form-item>
        <el-form-item label="所在地区">
          <el-cascader
            v-model="selectedArea"
            :options="areaData"
            placeholder="请选择省/市/区"
            clearable
          />
        </el-form-item>
        <el-form-item label="详细地址">
          <el-input
            v-model="editingAddress.address"
            type="textarea"
            :rows="2"
            placeholder="请输入详细地址"
          />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="editingAddress.isDefault">
            设为默认收货地址
          </el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveAddress">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<style scoped>
.address-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
}

.address-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.address-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
}

.address-item.is-default {
  border: 1px solid #67c23a;
}

.address-info {
  flex-grow: 1;
}

.address-header {
  margin-bottom: 10px;
}

.name {
  font-size: 16px;
  font-weight: bold;
  margin-right: 15px;
}

.phone {
  color: #666;
  margin-right: 15px;
}

.address-detail {
  color: #666;
  line-height: 1.5;
}

.address-actions {
  display: flex;
  gap: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>